package org.judo.security;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.judo.admin.identity.AppUser;
import org.judo.database.Database;
import org.judo.database.JudoDBConnection;
import org.judo.database.JudoDatabaseManager;
import org.judo.database.JudoResultSet;
import org.judo.menu.Menu;
import org.judo.menu.MenuItem;
import org.judo.propertyobject.PropertyObject;
import org.judo.util.Util;

public class SecurityManager
{
	private static HashMap protectedURLs = new HashMap();
	
	public static MenuItem[] cullMenuItems(AppUser user,Menu menu)
	{
		return menu.menuItems(user).toArray(new MenuItem[0]);
	}
	
	public static void addProtectedURL(String URL)
	{
		protectedURLs.put(URL,URL);
	}
	
	public static void removeProtectedURL(String URL)
	{
		protectedURLs.remove(URL);
	}
	
	public static boolean isProtectedURL(String URL)
	{
		Iterator urls = protectedURLs.keySet().iterator();
		
		while (urls.hasNext())
		{
			String url = (String)urls.next();
			
			if (URL.startsWith(url))
			{
				return true;
			}
		}
		
		return false;
	}

	public static void init()
		throws Exception
	{
		Database db = JudoDatabaseManager.getDatabase("sysDB");
		db.populateTransactionalConnection(JudoDatabaseManager.getConnection("sysDB"));
		
		JudoResultSet rs = db.query("select * from Site_Resource,Security_Rule where Site_Resource.siteResourceId = Security_Rule.siteResourceId");
		
		for (int i=0;i<rs.size();i++)
		{
			PropertyObject resc = (PropertyObject)rs.get(i);
			String url = (String)resc.get("url");
			Util.out("URL: "+url);
			protectedURLs.put(url,url);
		}
	}

	public static boolean passesSecurityCheck(AppUser user, String servletPath)
	{		
		if (isProtectedURL(servletPath))
		{
			if (user.canViewURL(servletPath))
				return true;
			else
				return false;
		}
		else
			return true;
	}
}
